package storage

import (
	"bufio"
	"bytes"
	"dog-blog/app/post/models"
	"dog-blog/base/utils/files"
	"dog-blog/base/utils/md"
	"log"
	"sort"
)

// basicData 配置数据
var basicData = &Basic{}

// articleMap 所有文章列表
var articleMap map[string]models.Article

// articleIds文章id索引表
var articleIds []string

// Load 加载配置
func Load() {
	loadBasic()
	LoadPost()
}

func loadBasic() {
	err := files.LoadYaml("conf/basic.yml", &basicData)
	if err != nil {
		panic(err)
	}
}

// LoadPost 加载文章
func LoadPost() {
	articleIds = []string{}
	articleMap = make(map[string]models.Article)

	mdByteList, err := files.LoadMdDir(basicData.Posts)
	if err != nil {
		log.Println(err)
		return
	}

	for _, mdByte := range mdByteList {
		article := md.ReadExtract(mdByte)
		if !article.IsEmpty() {
			articleMap[article.ID] = article
			articleIds = append(articleIds, article.ID)
		}
	}

	sort.Slice(articleIds, func(i, j int) bool {
		return articleMap[articleIds[i]].Time > articleMap[articleIds[j]].Time
	})
}

// GetBasic 获取基础配置
func GetBasic() *Basic {
	return basicData
}

// GetArticleMap 获取文章列表Map形式
func GetArticleMap() map[string]models.Article {
	return articleMap
}

// GetArticleByID 通过文章id获取文章
func GetArticleByID(id string) models.Article {
	return articleMap[id]
}

// GetArticleIds 获取文章索引列表
func GetArticleIds() []string {
	return articleIds
}

// FilterArticleIds 通过类型、具体值查询筛选文章id列表
func FilterArticleIds(typ string, fd string) []string {
	if typ == "" && fd == "" {
		return articleIds
	}

	ids1 := []string{}
	if typ != "" {
		for _, id := range articleIds {
			article := articleMap[id]
			if basicData.IsContainsCategory(typ, article.Category) {
				ids1 = append(ids1, id)
			}
		}
	} else {
		ids1 = articleIds
	}

	if fd == "" {
		return ids1
	}

	ids2 := []string{}
	for _, id := range ids1 {
		article := articleMap[id]
		input := bufio.NewScanner(bytes.NewReader(article.ContentByte))
		for input.Scan() {
			info := input.Bytes()
			if bytes.Contains(info, []byte(fd)) {
				ids2 = append(ids2, id)
				break
			}
		}
	}

	return ids2
}
